<script setup lang="ts">
import { onMounted,reactive,ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const form = reactive({
  enable: true,
  name: '',
  password: '',
  ip: ''
})
const interValId = ref<any>();
const buttonOk = ref<boolean>(true);

const getApStatus = async () => {
    try {
        const response = await axios.get('/api/ap-state')
        form.ip = response.data.ip
        form.name = response.data.name
        form.password = response.data.password
        form.enable = response.data.isEnable
        console.log(form)
        if(interValId.value){
            clearInterval(interValId.value);
        }
    } catch (error) {
        console.error('请求失败：', error)
    }
}

const checkAPState = async () => {
    interValId.value = setInterval(() => {
        getApStatus();  
    },1000)
}

const setApConfig = () => {
  ElMessageBox.confirm(
        '确认修改配置吗?',
        '请注意',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                buttonOk.value = false;
                // 设置ap信息
                const response = await axios.post('/api/ap-config', form)
                if (response.data) {
                    ElMessage.success('配置修改成功,请关注连接状态!')
                    // 通知开关
                    axios.get(`/api/ap-switch?enable=${form.enable}`)
                    // 检测状态
                    form.ip = '--';
                    form.enable = false;
                    checkAPState();
                }
                buttonOk.value = true;
            } catch (error) {
                console.error('请求失败：', error)
            }
        })
        .catch(err => console.log(err))
}

// 调用接口，查看当前AP状态
onMounted(() => {
    getApStatus();
})

</script>

<template>
  <el-form :model="form" label-width="200px" style="width: 600px">
    <el-form-item label="AP是否启用">
      <el-switch v-model="form.enable" class="ml-2"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
    </el-form-item>
    <el-form-item label="AP IP: ">
      <span>{{ form.ip }}</span>
    </el-form-item>
    <el-form-item label="AP名称: ">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="AP密码: ">
      <el-input v-model="form.password" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" :disabled="!buttonOk" @click="setApConfig">修改配置</el-button>
    </el-form-item>
  </el-form>
</template>

<style></style>
